import axios from 'axios'
import { getToken, removeToken } from './storage'
import history from 'utils/history'
import { message } from 'antd'
export const baseURL = 'http://geek.itheima.net/v1_0/'
const instance = axios.create({
  baseURL,
  timeout: 5000
})

// 请求拦截器
instance.interceptors.request.use(
  function (config) {
    const token = getToken()
    config.headers.Authorization = `Bearer ${token}`
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

// 响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response.data
  },
  function (error) {
    if (!error.response) {
      message.error('网络繁忙')
      return Promise.reject('网络繁忙')
    }
    // token过期处理
    if (error.response && error.response.status === 401) {
      console.log(history)
      removeToken()
      message.warn('登录信息过期了', 1)
      history.push('/login')
    }
    return Promise.reject(error)
  }
)

export default instance
